import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'
const http = axios.create({
  baseURL: 'http://localhost:51602/api', // 基地址
  timeout: 30000 // 超时时间 3s
})

http.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['token'] = token
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

// 3.响应拦截器
http.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    /***** 接收到异常响应的处理开始 *****/
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '错误请求'
          break
        case 401:
          error.message = '未授权，请重新登录'
          router.replace('/')
          localStorage.removeItem('token')
          localStorage.removeItem('user')
          break
        case 403:
          error.message = '拒绝访问'
          break
        case 404:
          error.message = '请求错误,未找到该资源'
          break
        case 405:
          error.message = '请求方法未允许'
          break
        case 408:
          error.message = '请求超时'
          break
        case 500:
          error.message = '服务器端出错'
          break
        case 502:
          error.message = '网络错误'
          break
        case 503:
          error.message = '服务器未就绪'
          break
        default:
          error.message = `连接错误 ${error.response.status}`
      }
    } else {
      error.message = '连接服务器失败'
    }
    ElMessage.error(error.message)
    return Promise.reject(error.response)
  }
)
export default http
